<template>
  <div class="edit-article">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span v-if="id">编辑文章</span>
        <span v-else>新增文章</span>
      </div>
      <div class="input-box">
        <el-form
          ref="editForm"
          :model="editForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="10">
              <div class="input-holder">
                <el-form-item label="标题" prop="title">
                  <el-input
                    v-model="editForm.title"
                    placeholder="请输入标题"
                    clearable
                    size="small"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="input-holder">
                <el-form-item label="作者" prop="author">
                  <el-input
                    v-model="editForm.author"
                    placeholder="请输入作者名"
                    clearable
                    size="small"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="input-holder">
                <el-form-item label="是否显示" prop="isShow">
                  <el-switch
                    v-model="editForm.isShow"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="input-holder">
                <el-form-item label="摘要" prop="summary">
                  <el-input
                    v-model="editForm.summary"
                    type="textarea"
                    placeholder="摘要"
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="input-holder">
                <el-form-item label="封面图片" prop="coverImg">
                  <el-upload
                    ref="imgUpload"
                    class="upload-demo"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="uploadSuccess"
                    multiple
                    :limit="1"
                    :file-list="fileList"
                  >
                    <el-button size="small" type="primary">点击上传素材</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>
                </el-form-item>
                <img class="img-preview" :src="editForm.coverImg" alt="">
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="input-holder">
                <el-form-item label="切换文本类型" prop="summary">
                  <el-radio v-model="editForm.editorType" :label="0" @change="radioChange">富文本</el-radio>
                  <el-radio v-model="editForm.editorType" :label="1" @change="radioChange">MarkDown</el-radio>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="16">
              <el-alert
                title="注意!切换编辑器会清空编辑内容"
                type="warning"
                show-icon
              />
            </el-col>
          </el-row>

          <div class="comp-holder">
            <template v-if="editForm.editorType===0">
              <el-upload
                ref="tinymceUpload"
                class="upload-demo"
                :action="uploadUrl"
                :headers="uploadHeaders"
                multiple
                :limit="1"
                :on-success="addTiImg"
              >
                <el-button size="small" type="primary">插入富文本图片</el-button>
              </el-upload>
              <tinymce ref="tinymce" v-model="editForm.content1" :height="300" />
            </template>
            <template v-else>
              <markdown-editor ref="markdown" v-model="editForm.content1" height="300px" />
            </template>
          </div>
          <el-form-item>
            <el-button
              class="submit"
              type="primary"
              @click="submitForm('editForm')"
            >立即提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import mixin from '@/mixins/index'
import Tinymce from '@/components/Tinymce'
import MarkdownEditor from '@/components/MarkdownEditor'
import {
  addArticle,
  productArticle,
  updataArticle
} from '@/api/content'

export default {

  components: { Tinymce, MarkdownEditor },
  mixins: [mixin],
  data() {
    return {
      // 修改时id
      id: '',
      // 上传时候的文件列表
      fileList: [],
      // 输入的数据
      editForm: {
        author: '',
        content1: '',
        coverImg: '',
        editorType: 0,
        isShow: 0,
        title: '',
        summary: ''
      },
      // 表单验证
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    console.log(this.$route.params)
    this.id = Reflect.get(this.$route.params, 'id')
    if (this.id) {
      this.getArticle()
    }
  },
  methods: {
    // 新增文章
    add() {
      addArticle(this.editForm).then(res => {
        if (res.code === 20000) {
          this.$message({
            type: 'success',
            message: '添加文章成功'
          })
          this.$router.go(-1)
        } else {
          this.$message({
            type: 'error',
            message: '添加文章失败'
          })
        }
        console.log(res)
      })
    },
    // 更新文章
    updata() {
      this.editForm.id = this.id
      updataArticle(this.editForm).then(res => {
        if (res.code === 20000) {
          this.$message({
            type: 'success',
            message: '更新文章成功'
          })
          this.$router.go(-1)
        } else {
          this.$message({
            type: 'error',
            message: '更新文章失败'
          })
        }
        console.log(res)
      })
    },
    // 单选框变化时清空内容（富文本还是markdown选择）
    radioChange() {
      this.editForm.content1 = ''
    },
    // 获取文章详情（edit）
    getArticle() {
      productArticle(this.id).then(res => {
        console.log(res)
        this.editForm = res.data.productArticle
      })
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.editForm)
          if (this.id) {
            this.updata()
          } else {
            this.add()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 上传图片成功的钩子
    uploadSuccess(res) {
      console.log(res)
      if (res.code === 20000) {
        this.editForm.coverImg = res.data.fileUrl
        this.$refs.imgUpload.clearFiles()
      }
    },
    // 在富文本中插入图片
    addTiImg(res, file) {
      this.$refs.tinymceUpload.clearFiles()
      this.$refs.tinymce.imageSuccessCBK([res.data.fileUrl])
    }
  }
}
</script>

@import '@/style/index.scss'
<style lang="scss" scoped>
.edit-article {
  .input-box {
    width: 100%;
    padding-right: 100px;

    .img-preview{
      padding-left: 100px;
    }

    .comp-holder{
      padding-left: 100px;
    }

    .submit{
      margin-top: 50px;
    }
  }
}
</style>
